﻿using BCService.Common.Sms;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Text;

namespace BCCommon
{
    public class SmsHelper:ISmsHelper
    {
        private readonly IConfiguration configuration;
        public SmsHelper(IConfiguration configuration)
        {
            this.configuration = configuration;
        }

        /// <summary>
        /// 发送手机短信。
        /// </summary>
        /// <param name="phone">手机号。</param>
        /// <param name="message">短信内容。</param>
        /// <returns></returns>
        public bool Send(string phone, string message)
        {
            Dictionary<string, string> postData = new Dictionary<string, string>
            {
                { "un", "N7039821" },
                { "pw", "6diA9LmpfR61d6" },
                { "phone", phone },
                { "msg", string.Format("{0}{1}", configuration["SmsService:signature"], message) },
                { "rd", "1" }
            };

            using (HttpClient httpClient = new HttpClient())
            {
                using (HttpResponseMessage responseMessage = httpClient.PostAsync(configuration["SmsService:postUrl"], new FormUrlEncodedContent(postData)).Result)
                {
                    string resultString = responseMessage.EnsureSuccessStatusCode().Content.ReadAsStringAsync().GetAwaiter().GetResult();

                    return resultString.Split('\n')[0].EndsWith(",0");
                }
            }
        }
    }
}
